package com.nf.health.app.datamain.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;

import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.http.Apis;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bluetools.BluetoothLeService;
import cn.bluetools.Pedometer_TypeInfo;
import cn.bluetools.ProtocolParser;

public class BraceletRemindActivity extends BaseActivity implements
        OnCheckedChangeListener {

    protected static final String TAG = BraceletRemindActivity.class
            .getSimpleName();
    @Bind(R.id.laidian)
    Button laidian;
    @Bind(R.id.weijie)
    Button weijie;
    @Bind(R.id.xiaoxi)
    Button xiaoxi;
    @Bind(R.id.youjian)
    Button youjian;
    @Bind(R.id.shejiao)
    Button shejiao;
    @Bind(R.id.rili)
    Button rili;
    @Bind(R.id.zhongwen)
    Button zhongwen;
    @Bind(R.id.yingwen)
    Button yingwen;
    @Bind(R.id.ll_test1)
    LinearLayout llTest1;
    @Bind(R.id.ll_test2)
    LinearLayout llTest2;
    private CheckBox cb_call_on;
    private CheckBox cb_mis_call_on;
    private CheckBox cb_sms_on;
    private CheckBox cb_email_on;
    private CheckBox cb_social_on;
    private CheckBox cb_calendar_on;
    private CheckBox cb_anti_lost_on;

    private int buttonId;
    private static final String ENABLED_NOTIFICATION_LISTENERS = "enabled_notification_listeners";
    private static final String ACTION_NOTIFICATION_LISTENER_SETTINGS = "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS";

    private ServiceConnection mServiceConnection;
    private BluetoothLeService mBluetoothLeService; // 蓝牙服务类
    private LocalBroadcastManager localBroadcastManager;
    /**
     * 接收蓝牙服务传入的事件消息，或者是接收到的蓝牙数据
     */
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
                    .equals(action)) {
                mBluetoothLeService.setANCS_SW(isCallON, isMisCallON, isSMSON,
                        isEmailON, isSocialON, iscalendarON, isAntiLostON);
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_TIMEOUT
                    .equals(action)) {
                // 蓝牙通讯超时，这里可以重发未响应的命令
                hideLoading();
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                // 蓝牙断开
                hideLoading();
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                // 接收到蓝牙数据
                hideLoading();
                byte[] bytes = intent
                        .getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                String s = ProtocolParser.bytes2HexString(bytes);
                LogUtil.e(TAG, "接收到数据:" + s + "\n");

                if (null == bytes)
                    return;
                if ((bytes.length == 6) && bytes[0] == 0x6e && bytes[1] == 0x01
                        && bytes[2] == 0x01 && bytes[5] == (byte) 0x8f
                        && isRemind) {
                    switch (buttonId) {
                        case R.id.cb_call_on:
                            showToast("设置成功");
                            PreferenceHelper.putBoolean(PreferenceHelper.isCallON,
                                    isCallON);
                            break;
                        case R.id.cb_mis_call_on:
                            showToast("设置成功");
                            PreferenceHelper.putBoolean(
                                    PreferenceHelper.isMisCallON, isMisCallON);
                            break;
                        case R.id.cb_sms_on:
                            showToast("设置成功");
                            PreferenceHelper.putBoolean(PreferenceHelper.isSMSON,
                                    isSMSON);
                            break;
                        case R.id.cb_social_on:
                            showToast("设置成功");
                            PreferenceHelper.putBoolean(
                                    PreferenceHelper.isSocialON, isSocialON);
                            break;
                        case R.id.cb_email_on:
                            showToast("设置成功");
                            PreferenceHelper.putBoolean(PreferenceHelper.isEmailON,
                                    isEmailON);
                            break;
                        case R.id.cb_calendar_on:
                            showToast("设置成功");
                            PreferenceHelper.putBoolean(
                                    PreferenceHelper.iscalendarON, iscalendarON);
                            break;
                        case R.id.cb_anti_lost_on:
                            showToast("设置成功");
                            PreferenceHelper.putBoolean(
                                    PreferenceHelper.isAntiLostON, isAntiLostON);
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    };
    private boolean isCallON;
    private boolean isMisCallON;
    private boolean isSMSON;
    private boolean isSocialON;
    private boolean isEmailON;
    private boolean iscalendarON;
    private boolean isAntiLostON;

    private boolean isRemind = false;
    private boolean isEnabledNLS = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        isRemind = true;
        setTitleBar(R.layout.layout_common_header);

        setContent(R.layout.activity_bracelet_remind);

        ViewUtil.setText(this, R.id.titlebar_title_tv, "提醒");
        ButterKnife.bind(this);
        initView();
        initListener();
        initBlueTooth();
        openNotificationAccess();
        if (Apis.HOST_COMMON.contains("test.")) {
            llTest1.setVisibility(View.VISIBLE);
            llTest2.setVisibility(View.VISIBLE);
        }
    }

    private void initListener() {
        laidian.setOnClickListener(this);
        weijie.setOnClickListener(this);
        xiaoxi.setOnClickListener(this);
        youjian.setOnClickListener(this);
        shejiao.setOnClickListener(this);
        rili.setOnClickListener(this);
        zhongwen.setOnClickListener(this);
        yingwen.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.laidian:
                mBluetoothLeService.setPushCallName("188888888");
                break;
            case R.id.weijie:
                mBluetoothLeService.setPushUCallNum(1);
                break;
            case R.id.xiaoxi:
//                byte[] array2 = new byte[]{110, 1, -77, 1, 8, 2, -113};
//                mBluetoothLeService.sendDataToPedometer(array2);
                mBluetoothLeService.setPushSMSNum(1);
                break;
            case R.id.youjian:
                mBluetoothLeService.setPushUEmailNum(1);
                break;
            case R.id.shejiao:
                mBluetoothLeService.setPushUSocNum(1);
                break;
            case R.id.rili:
                mBluetoothLeService.setPushUCalNum(1);
                break;
            case R.id.zhongwen:
//                showToast("暂无命令");
                byte[] command2 = new byte[]{0x6e, 0x01, 0x35, 0x01, (byte) 0x8f};
                mBluetoothLeService.sendDataToPedometer(command2);
                break;
            case R.id.yingwen:
//                showToast("暂无命令");
                byte[] command3 = new byte[]{0x6e, 0x01, 0x35, 0x00, (byte) 0x8f};
                mBluetoothLeService.sendDataToPedometer(command3);
                break;
            default:
                break;
        }
    }

    private boolean isEnabled() {
        String pkgName = getPackageName();
        final String flat = Settings.Secure.getString(getContentResolver(),
                ENABLED_NOTIFICATION_LISTENERS);
        if (!TextUtils.isEmpty(flat)) {
            final String[] names = flat.split(":");
            for (int i = 0; i < names.length; i++) {
                final ComponentName cn = ComponentName
                        .unflattenFromString(names[i]);
                if (cn != null) {
                    if (TextUtils.equals(pkgName, cn.getPackageName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 打开获取通知权限的入口
     */
    private void openNotificationAccess() {
        startActivity(new Intent(ACTION_NOTIFICATION_LISTENER_SETTINGS));
    }

    private void initBlueTooth() {
        localBroadcastManager = LocalBroadcastManager.getInstance(this);

        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName,
                                           IBinder service) {
                mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
                        .getService();
                // BluetoothLeService.setPedometerType(Pedometer_TypeInfo.Pedometer_Type.L28S);
                BluetoothLeService
                        .setPedometerType(Pedometer_TypeInfo.Pedometer_Type.L28T);
//                byte[] bytes = new byte[]{(byte)110, (byte)1, (byte)15, (byte)1, (byte)-113};//电池
//                byte[] bytes = new byte[]{(byte)110, (byte)1, (byte)3, (byte), (byte)-113};
//                mBluetoothLeService.sendDataToPedometer();
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                mBluetoothLeService = null;
            }
        };

        Intent bleService = new Intent(this, BluetoothLeService.class);
        bindService(bleService, mServiceConnection, Context.BIND_AUTO_CREATE);
        localBroadcastManager.registerReceiver(mGattUpdateReceiver,
                BluetoothLeService.makeGattUpdateIntentFilter());
    }

    private void initView() {
        cb_call_on = ViewUtil.getView(this, R.id.cb_call_on);
        cb_mis_call_on = ViewUtil.getView(this, R.id.cb_mis_call_on);
        cb_sms_on = ViewUtil.getView(this, R.id.cb_sms_on);
        cb_email_on = ViewUtil.getView(this, R.id.cb_email_on);
        cb_social_on = ViewUtil.getView(this, R.id.cb_social_on);
        cb_calendar_on = ViewUtil.getView(this, R.id.cb_calendar_on);
        cb_anti_lost_on = ViewUtil.getView(this, R.id.cb_anti_lost_on);

        isCallON = PreferenceHelper
                .getBoolean(PreferenceHelper.isCallON, false);
        isMisCallON = PreferenceHelper.getBoolean(PreferenceHelper.isMisCallON,
                false);
        isSMSON = PreferenceHelper.getBoolean(PreferenceHelper.isSMSON, false);
        isEmailON = PreferenceHelper.getBoolean(PreferenceHelper.isEmailON,
                false);
        isSocialON = PreferenceHelper.getBoolean(PreferenceHelper.isSocialON,
                false);
        iscalendarON = PreferenceHelper.getBoolean(
                PreferenceHelper.iscalendarON, false);
        isAntiLostON = PreferenceHelper.getBoolean(
                PreferenceHelper.isAntiLostON, false);

        cb_call_on.setChecked(isCallON);
        cb_mis_call_on.setChecked(isMisCallON);
        cb_sms_on.setChecked(isSMSON);
        cb_email_on.setChecked(isEmailON);
        cb_social_on.setChecked(isSocialON);
        cb_calendar_on.setChecked(iscalendarON);
        cb_anti_lost_on.setChecked(isAntiLostON);

        cb_anti_lost_on.setOnCheckedChangeListener(this);
        cb_calendar_on.setOnCheckedChangeListener(this);
        cb_email_on.setOnCheckedChangeListener(this);
        cb_social_on.setOnCheckedChangeListener(this);
        cb_sms_on.setOnCheckedChangeListener(this);
        cb_mis_call_on.setOnCheckedChangeListener(this);
        cb_call_on.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        buttonId = buttonView.getId();
        switch (buttonView.getId()) {
            case R.id.cb_call_on:
                isCallON = isChecked;
                break;
            case R.id.cb_mis_call_on:
                isMisCallON = isChecked;
                break;
            case R.id.cb_sms_on:
                isSMSON = isChecked;
                break;
            case R.id.cb_email_on:
                isEmailON = isChecked;
                break;
            case R.id.cb_social_on:
                isSocialON = isChecked;
                break;
            case R.id.cb_calendar_on:
                iscalendarON = isChecked;
                break;
            case R.id.cb_anti_lost_on:
                isAntiLostON = isChecked;
                break;
            default:
                break;
        }
        showLoading("设置中...");
        mBluetoothLeService.connect(PreferenceHelper.getString(
                PreferenceHelper.BLUETOOTH_DEVICE_ADDRESS, ""), "");
    }
}
